layui.define(function (exports) {
    "use strict";

    // jQuery
    const $ = layui.$

    //dom
    const parser = new DOMParser();

    // 组件内容
    let components = {}

    /**
     * jqGet
     * @param {string} url 
     * @returns string|error
     */
    const jqGet = async function (url) {
        try {
            const res = await $.get(url);
            return res;
        } catch (error) {
            // 处理错误的逻辑
            console.error(`组件页面加载失败: ${url}`);
            // 或者根据具体需求返回特定的值或执行其他错误处理操作
            return null;
        }
    }

    let sheet = new CSSStyleSheet()

    // 设置公共样式函数
    const setCommonStyle = async function () {
        let commonStyle = ""
        const commonDiv = document.querySelectorAll(`link[common]`)
        for (let index = 0; index < commonDiv.length; index++) {
            if (commonDiv[index].nodeName == "LINK") {
                commonStyle += await jqGet(commonDiv[index].getAttribute("href"))
            } else {
                continue
            }
        }
        sheet.replaceSync(commonStyle)
    }

    // 设置公共样式
    setCommonStyle()

    let comp = {
        render: async function (tag, href, isStyle = true) {
            let main = document.querySelector(tag)
            const shadow = main.attachShadow({ mode: "open" })
            let thisCss = new CSSStyleSheet()
            let StyleSheets = []
            // 默认样式
            if (isStyle) {
                StyleSheets.push(sheet)
            }
            // 获取模板内容
            let template = await jqGet(href)
            const dom = parser.parseFromString(template, "text/html")
            const scriptContent = dom.body.querySelector("script").textContent
            thisCss.replaceSync(dom.body.querySelector("style").textContent)
            dom.body.querySelector("script").remove()
            dom.body.querySelector("style").remove()
            StyleSheets.push(thisCss)
            shadow.adoptedStyleSheets = StyleSheets
            // 传值
            let data = {}
            for (let i = 0; i < main.attributes.length; i++) {
                data[main.attributes[i].name] = main.attributes[i].value
            }
            components[tag] = { document: shadow, data: data }
            let tpl = document.createElement("div")
            tpl.innerHTML = dom.body.innerHTML
            shadow.appendChild(tpl)
            let strict = document.createElement("script")
            strict.textContent = `(function(doc,data,tagName) {
            ${scriptContent}})(
            layui.comp.data['${tag}'].document,
            layui.comp.data['${tag}'].data,
            '${tag}')`
            shadow.appendChild(strict)
        },
        data: components
    }

    exports('comp', comp); // 输出模块
})